<template>
  <el-empty v-if="dailyItemInfo.itemList.length === 0" />

  <div v-else class="food-daily-item card-item">
    <daily-summary :date="dailyItemInfo.date"/>

    <div class="daily-list">
      <daily-card v-for="(item, index) in dailyItemInfo.itemList"
                  :key="index" @click="selectFoodRecordClick(item)"
                  :title="item.name" :content="item.category">
        <template #icon>
          <el-avatar>{{ item.category.charAt(0) }}</el-avatar>
        </template>

        <template #extra>
          <span>{{ item.person }}</span>
          <span>{{ item.date }}</span>
        </template>
      </daily-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import DailySummary from '@/components/DailySummary.vue'
import DailyCard from '@/components/DailyCard.vue'
import { defineProps, onMounted, reactive, watch } from 'vue'
import { useFoodStore } from '@/store/food.ts'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/store/app.ts'
import { formatChineseDate } from 'vue3-common/utils/dateUtil'
import { IFoodRecord } from '@/types/food.ts'
import { deepCopyObject } from 'vue3-common/utils/dataUtil'
import { isMobile } from 'vue3-common/utils/layoutUtil'

const foodStore = useFoodStore()
const appStore = useAppStore()
const router = useRouter()

const props = defineProps({
  date: {
    required: true,
    type: String
  }
})

watch(() => props.date, () => {
  getFoodDailyByDate(props.date as string)
})

watch(() => foodStore.isRefresh, () => {
  getFoodDailyByDate(props.date as string)
})

onMounted(() => {
  getFoodDailyByDate(props.date as string)
})

const dailyItemInfo = reactive({
  date: '',
  itemList: [] as IFoodRecord[]
})

/**
 * 根据日期获取当天的美食记录
 * @param date
 */
const getFoodDailyByDate = (date: string) => {
  if (date) {
    dailyItemInfo.date = formatChineseDate(date, 'MM月DD日 dddd')
    dailyItemInfo.itemList = []
    foodStore.foodRecordList.forEach((item) => {
      if (item.date === date) {
        dailyItemInfo.itemList.push(item)
      }
    })
  } else {
    dailyItemInfo.itemList = []
  }
}

/**
 * 点击美食记录按钮
 * @param foodRecord 美食记录
 */
const selectFoodRecordClick = async (foodRecord: IFoodRecord) => {
  foodStore.foodRecordApiType = 'UPDATE'

  if (isMobile()) {
    appStore.isShowMobileBack = true
    foodStore.currentFoodRecord = foodRecord
    await router.push({ name: 'FoodRecordForm' })
  } else {
    foodStore.foodRecordDialog = {
      title: '编辑记录',
      visible: true,
      data: deepCopyObject(foodRecord)
    }
  }
}
</script>

<style lang="scss">
.food-daily-item {
  display: flex;
  flex-direction: column;
  gap: 1vh;
  padding: 1vh 0.5vw;

  .daily-list {
    display: flex;
    flex-direction: column;
    gap: 1vh;
    overflow: auto;
  }
}
</style>
